<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF文档转换器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            padding: 40px;
            max-width: 800px;
            width: 100%;
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
        }

        .header h1 {
            color: #333;
            font-size: 2.5rem;
            margin-bottom: 10px;
            font-weight: 600;
        }

        .header p {
            color: #666;
            font-size: 1.1rem;
        }

        .upload-section {
            background: #f8f9fa;
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            margin-bottom: 30px;
            transition: all 0.3s ease;
        }

        .upload-section:hover {
            border-color: #667eea;
            background: #f0f2ff;
        }

        .upload-section.drag-over {
            border-color: #667eea;
            background: #e3f2fd;
            transform: scale(1.02);
        }

        .upload-icon {
            font-size: 3rem;
            color: #667eea;
            margin-bottom: 20px;
        }

        .file-input {
            display: none;
        }

        .upload-btn {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 25px;
            font-size: 1.1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 10px;
        }

        .upload-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .convert-btn, .download-btn, .convert-word-btn, .convert-image-btn {
            background: linear-gradient(45deg, #28a745, #20c997);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 25px;
            font-size: 1.1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 10px;
            display: none;
        }

        .convert-btn:hover, .download-btn:hover, .convert-word-btn:hover, .convert-image-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(40, 167, 69, 0.3);
        }
        
        .convert-word-btn {
            background: linear-gradient(45deg, #007bff, #0056b3);
        }
        
        .convert-word-btn:hover {
            box-shadow: 0 10px 20px rgba(0, 123, 255, 0.3);
        }
        
        .convert-image-btn {
            background: linear-gradient(45deg, #dc3545, #c82333);
        }
        
        .convert-image-btn:hover {
            box-shadow: 0 10px 20px rgba(220, 53, 69, 0.3);
        }

        .file-info {
            background: #e9ecef;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
            display: none;
        }

        .file-info h4 {
            color: #495057;
            margin-bottom: 10px;
        }

        .file-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            font-size: 0.9rem;
            color: #6c757d;
        }

        .result-section {
            margin-top: 30px;
            display: none;
        }

        .result-content {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            max-height: 400px;
            overflow-y: auto;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 0.9rem;
            line-height: 1.6;
            white-space: pre-wrap;
        }

        .loading {
            display: none;
            text-align: center;
            margin: 20px 0;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            margin: 20px auto;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .alert {
            padding: 15px;
            border-radius: 10px;
            margin: 20px 0;
            display: none;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .stats-section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-top: 30px;
            text-align: center;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 20px;
            margin-top: 15px;
        }

        .stat-item {
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .stat-value {
            font-size: 1.2rem;
            font-weight: bold;
            color: #667eea;
        }

        .stat-label {
            font-size: 0.9rem;
            color: #6c757d;
            margin-top: 5px;
        }

        @media (max-width: 768px) {
            .container {
                padding: 20px;
            }
            
            .header h1 {
                font-size: 2rem;
            }
            
            .file-details {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📄 PDF文档转换器</h1>
            <p>将您的PDF文档快速转换为Markdown、Word或图片格式</p>
        </div>

        <div class="upload-section" id="uploadSection">
            <div class="upload-icon">📁</div>
            <h3>选择或拖拽PDF文件</h3>
            <p>支持最大10MB的PDF文件</p>
            <input type="file" id="fileInput" class="file-input" accept=".pdf" />
            <button type="button" class="upload-btn" onclick="document.getElementById('fileInput').click()">
                选择文件
            </button>
        </div>

        <div class="file-info" id="fileInfo">
            <h4>文件信息</h4>
            <div class="file-details">
                <div>文件名: <span id="fileName"></span></div>
                <div>文件大小: <span id="fileSize"></span></div>
                <div>文件类型: <span id="fileType"></span></div>
                <div>上传时间: <span id="uploadTime"></span></div>
            </div>
        </div>

        <div style="text-align: center;">
            <button type="button" class="convert-btn" id="convertBtn" onclick="convertFile()">
                🔄 转换为Markdown
            </button>
            <button type="button" class="convert-word-btn" id="convertWordBtn" onclick="convertToWord()">
                📝 转换为Word
            </button>
            <button type="button" class="convert-image-btn" id="convertImageBtn" onclick="convertToImages()">
                🖼️ 转换为图片
            </button>
            <button type="button" class="download-btn" id="downloadBtn" onclick="downloadFile()">
                💾 下载Markdown文件
            </button>
        </div>

        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p>正在转换文件，请稍候...</p>
        </div>

        <div class="alert alert-success" id="successAlert"></div>
        <div class="alert alert-error" id="errorAlert"></div>

        <div class="result-section" id="resultSection">
            <h3>转换结果预览</h3>
            <div class="result-content" id="resultContent"></div>
        </div>

        <div class="stats-section">
            <h4>📊 服务信息</h4>
            <div class="stats-grid" id="statsGrid">
                <div class="stat-item">
                    <div class="stat-value" id="serverTime">--</div>
                    <div class="stat-label">服务器时间</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="maxFileSize">10MB</div>
                    <div class="stat-label">最大文件大小</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="supportedFormat">PDF</div>
                    <div class="stat-label">支持格式</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="version">1.0.0</div>
                    <div class="stat-label">版本号</div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let selectedFile = null;
        let convertedContent = null;

        // 页面加载时获取统计信息
        window.onload = function() {
            fetchStats();
        };

        // 获取服务统计信息
        function fetchStats() {
            fetch('/api/stats')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('serverTime').textContent = data.serverTime;
                    document.getElementById('maxFileSize').textContent = data.maxFileSize;
                    document.getElementById('supportedFormat').textContent = data.supportedFormats;
                    document.getElementById('version').textContent = data.version;
                })
                .catch(error => {
                    console.error('获取统计信息失败:', error);
                });
        }

        // 文件输入处理
        document.getElementById('fileInput').addEventListener('change', function(e) {
            handleFileSelect(e.target.files[0]);
        });

        // 拖拽功能
        const uploadSection = document.getElementById('uploadSection');
        
        uploadSection.addEventListener('dragover', function(e) {
            e.preventDefault();
            uploadSection.classList.add('drag-over');
        });

        uploadSection.addEventListener('dragleave', function(e) {
            e.preventDefault();
            uploadSection.classList.remove('drag-over');
        });

        uploadSection.addEventListener('drop', function(e) {
            e.preventDefault();
            uploadSection.classList.remove('drag-over');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFileSelect(files[0]);
            }
        });

        // 处理文件选择
        function handleFileSelect(file) {
            if (!file) {
                return;
            }

            if (!file.name.toLowerCase().endsWith('.pdf')) {
                showError('请选择PDF格式文件');
                return;
            }

            if (file.size > 10 * 1024 * 1024) {
                showError('文件大小不能超过10MB');
                return;
            }

            selectedFile = file;
            
            // 显示文件信息
            document.getElementById('fileName').textContent = file.name;
            document.getElementById('fileSize').textContent = formatFileSize(file.size);
            document.getElementById('fileType').textContent = file.type || 'application/pdf';
            document.getElementById('uploadTime').textContent = new Date().toLocaleString();
            
            document.getElementById('fileInfo').style.display = 'block';
            document.getElementById('convertBtn').style.display = 'inline-block';
            document.getElementById('convertWordBtn').style.display = 'inline-block';
            document.getElementById('convertImageBtn').style.display = 'inline-block';
            document.getElementById('downloadBtn').style.display = 'none';
            
            // 隐藏之前的结果
            document.getElementById('resultSection').style.display = 'none';
            hideAlerts();
        }

        // 转换文件
        function convertFile() {
            if (!selectedFile) {
                showError('请先选择文件');
                return;
            }

            const formData = new FormData();
            formData.append('file', selectedFile);

            showLoading(true);
            hideAlerts();

            fetch('/convert', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                showLoading(false);
                
                if (data.success) {
                    convertedContent = data.content;
                    document.getElementById('resultContent').textContent = data.content;
                    document.getElementById('resultSection').style.display = 'block';
                    document.getElementById('downloadBtn').style.display = 'inline-block';
                    showSuccess('转换成功！您可以预览结果或下载文件。');
                } else {
                    showError(data.message || '转换失败');
                }
            })
            .catch(error => {
                showLoading(false);
                console.error('转换失败:', error);
                showError('转换过程中发生错误，请稍后重试');
            });
        }
        
        // 转换为Word文档
        function convertToWord() {
            if (!selectedFile) {
                showError('请先选择文件');
                return;
            }

            const formData = new FormData();
            formData.append('file', selectedFile);

            showLoading(true);
            hideAlerts();

            fetch('/convert-to-word', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                showLoading(false);
                
                if (response.ok) {
                    return response.blob();
                } else {
                    throw new Error('转换失败');
                }
            })
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                
                const fileName = selectedFile.name.replace(/\.pdf$/i, '') + '_converted_' + 
                    new Date().toISOString().slice(0, 19).replace(/[:-]/g, '').replace('T', '_') + '.docx';
                a.download = fileName;
                
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                
                showSuccess('Word文档转换并下载成功！');
            })
            .catch(error => {
                showLoading(false);
                console.error('转换失败:', error);
                showError('转换为Word时发生错误');
            });
        }
        
        // 转换为图片
        function convertToImages() {
            if (!selectedFile) {
                showError('请先选择文件');
                return;
            }

            const formData = new FormData();
            formData.append('file', selectedFile);

            showLoading(true);
            hideAlerts();

            fetch('/convert-to-images', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                showLoading(false);
                
                if (response.ok) {
                    return response.blob();
                } else {
                    throw new Error('转换失败');
                }
            })
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                
                const fileName = selectedFile.name.replace(/\.pdf$/i, '') + '_images_' + 
                    new Date().toISOString().slice(0, 19).replace(/[:-]/g, '').replace('T', '_') + '.zip';
                a.download = fileName;
                
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                
                showSuccess('图片转换并下载成功！包含所有页面的图片文件。');
            })
            .catch(error => {
                showLoading(false);
                console.error('转换失败:', error);
                showError('转换为图片时发生错误');
            });
        }

        // 下载文件
        function downloadFile() {
            if (!selectedFile) {
                showError('请先选择并转换文件');
                return;
            }

            const formData = new FormData();
            formData.append('file', selectedFile);

            showLoading(true);

            fetch('/download', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                showLoading(false);
                
                if (response.ok) {
                    return response.blob();
                } else {
                    throw new Error('下载失败');
                }
            })
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                
                const fileName = selectedFile.name.replace(/\.pdf$/i, '') + '_converted_' + 
                    new Date().toISOString().slice(0, 19).replace(/[:-]/g, '').replace('T', '_') + '.md';
                a.download = fileName;
                
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                
                showSuccess('文件下载成功！');
            })
            .catch(error => {
                showLoading(false);
                console.error('下载失败:', error);
                showError('下载文件时发生错误');
            });
        }

        // 显示加载状态
        function showLoading(show) {
            document.getElementById('loading').style.display = show ? 'block' : 'none';
        }

        // 显示成功消息
        function showSuccess(message) {
            const alert = document.getElementById('successAlert');
            alert.textContent = message;
            alert.style.display = 'block';
            setTimeout(() => {
                alert.style.display = 'none';
            }, 5000);
        }

        // 显示错误消息
        function showError(message) {
            const alert = document.getElementById('errorAlert');
            alert.textContent = message;
            alert.style.display = 'block';
            setTimeout(() => {
                alert.style.display = 'none';
            }, 5000);
        }

        // 隐藏所有提示消息
        function hideAlerts() {
            document.getElementById('successAlert').style.display = 'none';
            document.getElementById('errorAlert').style.display = 'none';
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    </script>
</body>
</html>